package com.gzdh.dishrecognition.util;

import android.content.Context;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.Surface;
import android.view.TextureView;

import com.gzdh.dishrecognition.config.IdfConst;
import com.gzdh.dishrecognition.ui.view.AutoFitTextureView;

import java.util.List;

/**
 * Time: 2019/1/24
 * Author: v_chaixiaogang
 * Description:
 */
public class CameraPreviewManager implements TextureView.SurfaceTextureListener {

    private static final String TAG = "camera_preview";

    AutoFitTextureView mTextureView;
    private SurfaceTexture mSurfaceTexture;

    private int previewWidth;
    private int previewHeight;

    private Camera mCamera;

    private CameraDataCallback mCameraDataCallback;
    private static volatile CameraPreviewManager instance = null;

    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

    static {

        ORIENTATIONS.append(Surface.ROTATION_0, 0);
        ORIENTATIONS.append(Surface.ROTATION_90, 90);
        ORIENTATIONS.append(Surface.ROTATION_180, 180);
        ORIENTATIONS.append(Surface.ROTATION_270, 270);
    }

    private Context mContext;


    private int cameraFacing;

    public static CameraPreviewManager getInstance() {
        synchronized (CameraPreviewManager.class) {
            if (instance == null) {
                instance = new CameraPreviewManager();
            }
        }
        return instance;
    }

    /**
     * 开启预览
     *
     * @param context
     * @param textureView
     */
    public void startPreview(Context context, AutoFitTextureView textureView,   CameraDataCallback cameraDataCallback) {
        Log.e(TAG, "开启预览模式");
        mContext = context;
         this.mCameraDataCallback = cameraDataCallback;
        mTextureView = textureView;
        mSurfaceTexture = mTextureView.getSurfaceTexture();
        mTextureView.setSurfaceTextureListener(this);
    }

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
        Log.e(TAG, "--surfaceTexture--SurfaceTextureAvailable");
        mSurfaceTexture = texture;
        openCamera();
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int i, int i1) {
        Log.e(TAG, "--surfaceTexture--TextureSizeChanged");
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
        Log.e(TAG, "--surfaceTexture--destroyed");
        if (mCamera != null) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture texture) {
        // Log.e(TAG, "--surfaceTexture--Updated");
    }

    /**
     * 关闭预览
     */
    public void stopPreview() {
        if (mCamera != null) {
            try {
                mCamera.setPreviewTexture(null);
                mTextureView = null;
                mCamera.setPreviewCallback(null);
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
            } catch (Exception e) {
                Log.e("qing", "camera destory error");
                e.printStackTrace();

            }
        }
    }

    /**
     * 开启摄像头
     */

    public void openCamera() {
        try {
            if (mCamera == null) {
                CameraManager cameraManager = (CameraManager) mContext.getSystemService(Context.CAMERA_SERVICE);
                String[] cameraIdList = cameraManager.getCameraIdList();
                for (int i = 0; i < cameraIdList.length; i++) {
                    String camera_id = cameraIdList[i];
                    if (IdfConst.getInstance().getCameraId().equals(camera_id)) {
                        cameraFacing = i;//默认使用后置相机
                        break;
                    }
                }
                System.out.println("主屏摄像头" + cameraFacing);
                mCamera = Camera.open(cameraFacing);
                Log.e(TAG, "initCamera---open camera");
            }

            Camera.Parameters params = mCamera.getParameters();
            List<Camera.Size> sizeList = params.getSupportedPreviewSizes(); // 获取所有支持的camera尺寸

            previewWidth = IdfConst.getInstance().getWidth();
            previewHeight = IdfConst.getInstance().getHeight();
            if (previewWidth == 0 || previewHeight == 0) {
                Camera.Size size = sizeList.get(0);
                previewWidth = size.width;
                previewHeight = size.height;
            }
            params.setPreviewSize(previewWidth, previewHeight);
            mTextureView.setAspectRation(previewWidth, previewHeight);
//            params.setZoom((int) systemSettingObject.getZoomLevel());
            mCamera.setParameters(params);
            try {
                mCamera.setPreviewTexture(mSurfaceTexture);
                mCamera.setPreviewCallback((bytes, camera) -> {
                    if (mCameraDataCallback != null) {
                        mCameraDataCallback.onGetCameraData(bytes, camera,
                                previewWidth, previewHeight);
                    }
                });
                mCamera.startPreview();
                if (mCameraDataCallback != null) {
                    int[] range = new int[2];
                    params.getPreviewFpsRange(range);
                    mCameraDataCallback.onOpened(range);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
        } catch (RuntimeException | CameraAccessException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    public List<Camera.Size> getCameraSize() {
        if (mCamera == null) {
            return null;
        }
        Camera.Parameters parameters = mCamera.getParameters();
        List<Camera.Size> sizeList = parameters.getSupportedPreviewSizes();
        return sizeList;
    }

    /**
     * 获取最大Zoom值
     *
     * @return zoom
     */
    public int getMaxZoom() {
        if (mCamera == null) {
            return -1;
        }
        Camera.Parameters parameters = mCamera.getParameters();
        if (!parameters.isZoomSupported()) {
            return -1;
        }
        return parameters.getMaxZoom() > 50 ? 50 : parameters.getMaxZoom();
    }

    /**
     * 变焦
     *
     * @param zoom 缩放系数
     */
    public void setZoom(int zoom) {
        if (mCamera == null) {
            return;
        }
        //获取Paramters对象
        Camera.Parameters parameters = mCamera.getParameters();
        //如果不支持变焦
        if (!parameters.isZoomSupported()) {
            return;
        }
        //
        parameters.setZoom(zoom);
        //Camera对象重新设置Paramters对象参数
        mCamera.setParameters(parameters);
    }

    public int getPreviewWidth() {
        return previewWidth;
    }

    public int getPreviewHeight() {
        return previewHeight;
    }

    public int getCameraFacing() {
        return cameraFacing;
    }
}
